package com.training.schedule_management_system_admin.config;

import com.training.schedule_management_system_admin.entity.Role;
import com.training.schedule_management_system_admin.entity.User;
import com.training.schedule_management_system_admin.service.UserService;
import com.training.schedule_management_system_admin.utils.MD5Utils;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /*
    授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        //SimpleAuthorizationInfo授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //拿到当前登录的这个对象
        Subject subject= SecurityUtils.getSubject();
        //拿到用户对象
        User currentUser = (User)subject.getPrincipal();
        //根据当前用户的id查询其所拥有的所有角色
        User user = userService.getUserWithRole(currentUser.getId());
        //将其拥有的所有角色添加到List集合
        List<String> roles = new ArrayList<>();
        for (Role role:user.getRoles()){
            roles.add(role.getRole());
        }
        //设置当前用户的角色
        info.addRoles(roles);
        return info;
    }

    /*
    认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        //判断用户名是否存在
        User user = userService.getUserByUsername(token.getUsername());
        if(user==null) {
            return null;//若用户名不存在，抛出异常UnknownAccountException
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);
        return new SimpleAuthenticationInfo(user, user.getPassword(),"");//若密码不正确，抛出异常IncorrectCredentialsException
    }
}
